package com.basic.im.pay.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.basic.im.pay.controller.secondpay.ChargeWay;
import com.basic.im.pay.controller.secondpay.ThirdPay;
import com.basic.im.pay.controller.secondpay.ChargeWayAll;
import com.basic.im.pay.controller.secondpay.utils.HttpUtil;
import com.basic.im.pay.controller.secondpay.utils.SignUtil;
import com.basic.im.pay.dto.ConsumRecordCountDTO;
import com.google.common.collect.Maps;
import com.basic.common.model.PageResult;
import com.basic.common.model.PageVO;
import com.basic.im.api.service.base.AbstractController;
import com.basic.im.comm.constants.KConstants;
import com.basic.im.comm.ex.ServiceException;
import com.basic.im.comm.utils.ReqUtil;
import com.basic.im.i18n.LocaleMessageUtils;
import com.basic.im.pay.constants.ConsumeRecordEnum;
import com.basic.im.pay.constants.PayResultCode;
import com.basic.im.pay.entity.BaseConsumeRecord;
import com.basic.im.pay.service.impl.ConsumeRecordManagerImpl;
import com.basic.im.api.service.AuthServiceOldUtils;
import com.basic.im.user.config.WXConfig;
import com.basic.im.user.service.UserCoreService;
import com.basic.im.utils.SKBeanUtils;
import com.basic.im.vo.JSONMessage;
import com.basic.utils.DateUtil;
import com.basic.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.bson.types.ObjectId;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;

import static com.basic.im.pay.controller.secondpay.SecondPay.genUrlParams;
import static com.basic.im.pay.controller.secondpay.ThirdPay.MERCHANT_KEY;


@RestController
@Api(value="ConsumeRecordController",tags="消费记录接口")
@RequestMapping(value = "",method = {RequestMethod.POST,RequestMethod.GET})
public class ConsumeRecordController extends AbstractController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private ConsumeRecordManagerImpl consumeRecordManager;

	@Autowired
	private UserCoreService userCoreService;

	@Autowired
	private WXConfig wxConfig;


	@Autowired
	private AuthServiceOldUtils authServiceOldUtils;

@Autowired
	private RedissonClient redissonClient;

	@Value("${tszfaa.url}")
	private String tszfaaUrl;
	@Value("${tszfaa.paykey}")
	private String tszfaaKey;
	@Value("${tszfaa.paySecret}")
	private String tszfaaSecret;
	@Value("${tszfaa.notifyUrl}")
	private String tszfaaNotifyUrl;

    @Value("${kkzf.notifyUrl}")
    private String kkzfNotifyUrl;

	public static void main(String[] args) {
		Map<String, Object> nativeParams = new TreeMap<>();
		nativeParams.put("mchKey", "MCHr1gpO9Ufpo");

		nativeParams.put("mchOrderNo", IdUtil.simpleUUID()); // 金额单位为分
		nativeParams.put("amount", (int) (1*100));
		nativeParams.put("nonce", RandomUtil.randomString(10));
		nativeParams.put("timestamp", System.currentTimeMillis());
		nativeParams.put("notifyUrl", "/alipay/tszfaaCallBack"); // 未初始化
		nativeParams.put("product", "9999");

		StringBuilder md5Str = new StringBuilder();
		nativeParams.forEach((key, value) -> md5Str.append(key).append("=").append(value).append("&"));
		md5Str.deleteCharAt(md5Str.length() - 1).append("kysm8cXmG2P2ZzvMbQLtKVy");
		String sign = SecureUtil.md5(md5Str.toString()).toUpperCase();
		nativeParams.put("sign", sign);
//		String post = HttpUtil.post("https://tsapi-shenglongyun.tszfaa.com/api/v1/payment/init", nativeParams);

		HttpResponse response = HttpRequest.post("https://tsapi-aipay.tszfaa.com/api/v1/payment/init")
				.body(JSONUtil.toJsonStr(nativeParams),"application/json; charset=utf-8")
				.timeout(15000)
				.execute();
		if(response.getStatus() == 200){
			JSONObject jsonObject = JSONUtil.parseObj(response.body());
			String code = (String) jsonObject.get("code");
			if("200".equals(code)){
				String payUrl = (String) jsonObject.getJSONObject("data").getJSONObject("url").get("payUrl");
				System.out.println(payUrl);
			}else{
				System.out.println((String) jsonObject.get("msg"));

			}
		}
	}


	public List<String> getRedisConfig(String key){
        List<String> temp = new ArrayList<>();
	    String result = (String) redissonClient.getBucket(key).get();
	    if(StringUtil.isEmpty(result)){
	        return temp;
        }
	    if (result.contains("-")){
	        return Arrays.asList(result);
        }else {

	        String[] s = result.split(" ");
	        for (int i=0;i<s.length;i++){
	            if (!StringUtil.isEmpty(s[i])) {
                    temp.add(s[i].trim());
                }
            }

	        return temp;
        }
    }

	@RequestMapping(value = "/rechargeInterval")
	public JSONMessage rechargeInterval(){


        List<ChargeWayAll> list = new ArrayList<>();


        if(!redissonClient.getSet("USER_FIRST_RECHARGE").contains(ReqUtil.getUserId())) {
            List<ChargeWay> chargeWayList1 = new ArrayList<>();
            chargeWayList1.add(new ChargeWay("支付宝原生", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "1", Arrays.asList(redissonClient.getBucket("rechargeInterval_min").get()+"-9999999"), true));

            chargeWayList1.add(new ChargeWay("qq话费", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "8", getRedisConfig("qqf"), true));
            chargeWayList1.add(new ChargeWay("奥特莱斯礼品卡", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "9", getRedisConfig("atlsf"), false));
            chargeWayList1.add(new ChargeWay("数字人民币", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "10", getRedisConfig("numf"), false));
            chargeWayList1.add(new ChargeWay("手机银行", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "11", getRedisConfig("bankpf"), false));


            List<ChargeWay> chargeWayList2 = new ArrayList<>();
            chargeWayList2.add(new ChargeWay("支付宝旗舰店", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "12",getRedisConfig("zfbf"), false));
            chargeWayList2.add(new ChargeWay("手机银行", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "13", getRedisConfig("bankpsf"), false));
            chargeWayList2.add(new ChargeWay("支付宝内层原生", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "14", getRedisConfig("zfb2f"), true));
            chargeWayList2.add(new ChargeWay("综合支付", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "15", getRedisConfig("zhf"), true));

            List<ChargeWay> chargeWayList3 = new ArrayList<>();
            chargeWayList3.add(new ChargeWay("USDT", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "16", getRedisConfig("usdtf"), true));

            list.add(new ChargeWayAll("通道一", chargeWayList1));
            list.add(new ChargeWayAll("通道二", chargeWayList2));
            list.add(new ChargeWayAll("通道三", chargeWayList3));
        }else{
            List<ChargeWay> chargeWayList1 = new ArrayList<>();

            chargeWayList1.add(new ChargeWay("qq话费", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "8", getRedisConfig("qqs"), true));
            chargeWayList1.add(new ChargeWay("奥特莱斯礼品卡", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "9", getRedisConfig("atlss"), false));
            chargeWayList1.add(new ChargeWay("数字人民币", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "10", getRedisConfig("nums"), false));
            chargeWayList1.add(new ChargeWay("手机银行", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "11", getRedisConfig("bankps"), false));


            List<ChargeWay> chargeWayList2 = new ArrayList<>();
            chargeWayList2.add(new ChargeWay("支付宝旗舰店", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "12", getRedisConfig("zfbs"), false));
            chargeWayList2.add(new ChargeWay("手机银行", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "13",  getRedisConfig("bankpss"), false));
            chargeWayList2.add(new ChargeWay("支付宝内层原生", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "14", getRedisConfig("zfb2s"), true));
            chargeWayList2.add(new ChargeWay("综合支付", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "15",getRedisConfig("zhs"), true));

            List<ChargeWay> chargeWayList3 = new ArrayList<>();
            chargeWayList3.add(new ChargeWay("USDT", "https://i-blog.csdnimg.cn/direct/582b069abe054a5a8ac80444e7baf876.jpeg", "16", getRedisConfig("usdts"), true));

            list.add(new ChargeWayAll("通道一", chargeWayList1));
            list.add(new ChargeWayAll("通道二", chargeWayList2));
            list.add(new ChargeWayAll("通道三", chargeWayList3));
        }


		double rechargeInterval_min = (double) redissonClient.getBucket("rechargeInterval_min").get();
		double rechargeInterval_max = (double) redissonClient.getBucket("rechargeInterval_max").get();
		double second_rechargeInterval_min = (double) redissonClient.getBucket("second_rechargeInterval_min").get();
		double second_rechargeInterval_max = (double) redissonClient.getBucket("second_rechargeInterval_max").get();
		Map<String,Object> map= Maps.newLinkedHashMap();
		map.put("min", rechargeInterval_min);
		map.put("max", rechargeInterval_max);
		map.put("second_rechargeInterval_min", second_rechargeInterval_min);
		map.put("second_rechargeInterval_max", second_rechargeInterval_max);
		map.put("isfirstCharge", redissonClient.getSet("USER_FIRST_RECHARGE").contains(ReqUtil.getUserId())?0:1);
		map.put("chargelist",list);
		return JSONMessage.success(null,map);
	}


	@RequestMapping(value = "/tszfaaquery")
	public JSONMessage tszfaaquery( @RequestParam String orderNo){
//		Map<String, Object> nativeParams = new TreeMap<>();
//		nativeParams.put("mchKey", tszfaaKey);
//
//		nativeParams.put("mchOrderNo", orderNo); // 金额单位为分
//		nativeParams.put("nonce", RandomUtil.randomString(10));
//		nativeParams.put("timestamp", System.currentTimeMillis());
//		StringBuilder md5Str = new StringBuilder();
//		nativeParams.forEach((key, value) -> md5Str.append(key).append("=").append(value).append("&"));
//		md5Str.deleteCharAt(md5Str.length() - 1).append(tszfaaSecret);
//		String sign = SecureUtil.md5(md5Str.toString()).toUpperCase();
//		nativeParams.put("sign", sign);
//
//		HttpResponse response = HttpRequest.post(tszfaaUrl+"/api/v1/payment/query")
//				.body(JSONUtil.toJsonStr(nativeParams),"application/json; charset=utf-8")
//				.timeout(15000)
//				.execute();
//		if(response.getStatus() == 200){
//			logger.info("---------------------{}",response.body());
//			JSONObject jsonObject = JSONUtil.parseObj(response.body());
//			String code = (String) jsonObject.get("code");
//			if(!"200".equals(code)){
//				return JSONMessage.failure((String) jsonObject.get("msg"));
//			}
//			String payStatus = (String) jsonObject.getJSONObject("data").get("payStatus");
//			Map<String,String> map= Maps.newLinkedHashMap();
//			map.put("payStatus", payStatus);
//			return JSONMessage.success(null,map);
//		}
//		return JSONMessage.failure("接口请求失败");

        BaseConsumeRecord entity = consumeRecordManager.getConsumeRecordByNo(orderNo);
        if (null == entity) {
            logger.info("交易订单号不存在！-----" + orderNo);
            return JSONMessage.failure("接口请求失败");
        }else{
            Map<String,String> map= Maps.newLinkedHashMap();
			map.put("payStatus", "SUCCESS");
			return JSONMessage.success(null,map);
        }
    }

	/**
	 * 充值
	 * @param payType
	 * @param price
	 * @param time
	 * @param secret
	 * @return
	 */
	@ApiOperation("充值")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType="query" , name="payType",value="支付类型",dataType="int"),
			@ApiImplicitParam(paramType="query" , name="price",value="价格",dataType="String"),
			@ApiImplicitParam(paramType="query" , name="time",value="时间",dataType="String"),
			@ApiImplicitParam(paramType="query" , name="secret",value="加密数据",dataType="String"),
			@ApiImplicitParam(paramType="query" , name="salt",value="盐加密",dataType="String")
	})
	@RequestMapping(value = "/user/recharge/getSign")
	@Deprecated
	public JSONMessage getSign(HttpServletRequest request, @RequestParam int payType, @RequestParam String price,
							   @RequestParam(defaultValue="0") long time,
							   @RequestParam(defaultValue="") String secret, String salt) {

		String token=getAccess_token();
		Integer userId = ReqUtil.getUserId();
		if(StringUtil.isEmpty(salt)){
			//充值接口授权
			if(!authServiceOldUtils.authRedPacket(userId+"", token, time, secret)) {
				return JSONMessage.failureByErrCode(KConstants.ResultCode.AUTH_FAILED);
			}
		}
		// 处理充值自定义输入金额超过两位数
		DecimalFormat df = new DecimalFormat("0.00");
		Double money = new Double(price);
		if(0.01>money){
			return JSONMessage.failureByErrCode(PayResultCode.PleaseEnterAmount);
		}
		// 判断单笔消费金额是否超过限制
		if(money>SKBeanUtils.getImCoreService().getPayConfig().getMaxRechargeAmount()){
			return JSONMessage.failureByErrCode(PayResultCode.ExceedMaxAmount);
		}
		// 判断单日消费金额是否超过限制
		Double todayMoney = consumeRecordManager.getUserPayMoney(userId,KConstants.ConsumeType.USER_RECHARGE,KConstants.OrderStatus.END, DateUtil.getTodayMorning().getTime()/1000 , DateUtil.getTodayNight().getTime()/1000);
		todayMoney = todayMoney + money;
		if(todayMoney > SKBeanUtils.getImCoreService().getPayConfig().getDayMaxRechargeAmount()){
			return JSONMessage.failureByErrCode(PayResultCode.ExceedDayMaxAmount);
		}

		price = df.format(money);
		Map<String,String> map= Maps.newLinkedHashMap();
		String orderInfo="";
		if(0<payType){
			String orderNo=StringUtil.getOutTradeNo();
			BaseConsumeRecord entity=new BaseConsumeRecord();
			entity.setMoney(money);
			/*if(10<entity.getMoney()) {
				return JSONMessage.failureByErrCode(PayResultCode.SingleRechargeUpTen);
			}*/
			entity.setUserId(ReqUtil.getUserId());
			entity.setTime(DateUtil.currentTimeSeconds());
			entity.setType(KConstants.ConsumeType.USER_RECHARGE);
			entity.setChangeType(KConstants.MOENY_ADD);
			entity.setDesc("余额充值");
			//entity.setDesc("Balance recharge");
			entity.setStatus(KConstants.OrderStatus.CREATE);
			entity.setTradeNo(orderNo);
			entity.setPayType(payType);

			Map<String, Object> nativeParams = new TreeMap<>();
			nativeParams.put("mchKey", tszfaaKey);

			nativeParams.put("mchOrderNo", orderNo); // 金额单位为分
			nativeParams.put("amount", (int) (money*100));
			nativeParams.put("nonce", RandomUtil.randomString(10));
			nativeParams.put("timestamp", System.currentTimeMillis());
			nativeParams.put("notifyUrl", tszfaaNotifyUrl); // 未初始化
			nativeParams.put("attach",userId+"");


			if (KConstants.PayType.ALIPAY == payType) {
				nativeParams.put("product", "1010");

//				if(1 != SKBeanUtils.getImCoreService().getClientConfig().getEnableAliPay()){
//					return JSONMessage.failureByErrCode(KConstants.ResultCode.FUNCTION_NOTOPEN);
//				}
//
//				orderInfo = AliPayUtil.getOrderInfo("余额充值", "余额充值", price, orderNo);
//				consumeRecordManager.saveConsumeRecord(entity);
//				map.put("orderInfo", orderInfo);
//
//				logger.info("orderInfo : " + orderInfo);
//				return JSONMessage.success(null, map);
			}else if(KConstants.PayType.WXPAY == payType) {
				nativeParams.put("product", "P0000");

//				if(1 != SKBeanUtils.getImCoreService().getClientConfig().getEnableWxPay()){
//					return JSONMessage.failureByErrCode(KConstants.ResultCode.FUNCTION_NOTOPEN);
//				}
//				WxPayDto tpWxPay = new WxPayDto();
//				//tpWxPay.setOpenId(openId);
//				tpWxPay.setBody("余额充值");
//				tpWxPay.setOrderId(orderNo);
//				tpWxPay.setSpbillCreateIp(request.getRemoteAddr());
//				tpWxPay.setTotalFee(price);
//				consumeRecordManager.saveConsumeRecord(entity);
//				Object data= WXPayUtil.getPackage(tpWxPay,wxConfig);
//				return JSONMessage.success(data);
			}else{
				nativeParams.put("product", "1016");
			}
			StringBuilder md5Str = new StringBuilder();
			nativeParams.forEach((key, value) -> md5Str.append(key).append("=").append(value).append("&"));
			md5Str.deleteCharAt(md5Str.length() - 1).append(tszfaaSecret);
			String sign = SecureUtil.md5(md5Str.toString()).toUpperCase();
			nativeParams.put("sign", sign);
			HttpResponse response = HttpRequest.post(tszfaaUrl+"/api/v1/payment/init")
					.body(JSONUtil.toJsonStr(nativeParams),"application/json; charset=utf-8")
					.timeout(15000)
					.execute();
			if(response.getStatus() == 200){
				consumeRecordManager.saveConsumeRecord(entity);
				logger.info("---------------------{}",response.body());
				JSONObject jsonObject = JSONUtil.parseObj(response.body());
				String code = (String) jsonObject.get("code");
				if(!"200".equals(code)){
					return JSONMessage.failure((String) jsonObject.get("msg"));
				}
				String payUrl = (String) jsonObject.getJSONObject("data").getJSONObject("url").get("payUrl");
				map.put("payUrl", payUrl);
				map.put("orderNo",orderNo);
				return JSONMessage.success(null,map);
			}
		}
		return JSONMessage.failureByErrCode(PayResultCode.NotSelectPayType);
	}


	@RequestMapping(value = "/getSignV2")
	public JSONMessage getSignV2(HttpServletRequest request, @RequestParam int payType, @RequestParam String price,
							   @RequestParam(defaultValue="0") long time,
							   @RequestParam(defaultValue="") String secret, String salt) {

		String token=getAccess_token();
		Integer userId = ReqUtil.getUserId();
		if(StringUtil.isEmpty(salt)){
			//充值接口授权
			if(!authServiceOldUtils.authRedPacket(userId+"", token, time, secret)) {
				return JSONMessage.failureByErrCode(KConstants.ResultCode.AUTH_FAILED);
			}
		}
		// 处理充值自定义输入金额超过两位数
		DecimalFormat df = new DecimalFormat("0.00");
		Double money = new Double(price);
		if(0.01>money){
			return JSONMessage.failureByErrCode(PayResultCode.PleaseEnterAmount);
		}
		// 判断单笔消费金额是否超过限制
		if(money>SKBeanUtils.getImCoreService().getPayConfig().getMaxRechargeAmount()){
			return JSONMessage.failureByErrCode(PayResultCode.ExceedMaxAmount);
		}
		// 判断单日消费金额是否超过限制
		Double todayMoney = consumeRecordManager.getUserPayMoney(userId,KConstants.ConsumeType.USER_RECHARGE,KConstants.OrderStatus.END, DateUtil.getTodayMorning().getTime()/1000 , DateUtil.getTodayNight().getTime()/1000);
		todayMoney = todayMoney + money;
		if(todayMoney > SKBeanUtils.getImCoreService().getPayConfig().getDayMaxRechargeAmount()){
			return JSONMessage.failureByErrCode(PayResultCode.ExceedDayMaxAmount);
		}

		price = df.format(money);
		Map<String,String> map= Maps.newLinkedHashMap();
		String orderInfo="";
		if(0<payType){
			String orderNo=StringUtil.getOutTradeNo();
			BaseConsumeRecord entity=new BaseConsumeRecord();
			entity.setMoney(money);
			/*if(10<entity.getMoney()) {
				return JSONMessage.failureByErrCode(PayResultCode.SingleRechargeUpTen);
			}*/
			entity.setUserId(ReqUtil.getUserId());
			entity.setTime(DateUtil.currentTimeSeconds());
			entity.setType(KConstants.ConsumeType.USER_RECHARGE);
			entity.setChangeType(KConstants.MOENY_ADD);
			entity.setDesc("余额充值");
			//entity.setDesc("Balance recharge");
			entity.setStatus(KConstants.OrderStatus.CREATE);
			entity.setTradeNo(orderNo);
			entity.setPayType(payType);

			Map<String, Object> nativeParams = new TreeMap<>();
			nativeParams.put("mchKey", tszfaaKey);

			nativeParams.put("mchOrderNo", orderNo); // 金额单位为分
			nativeParams.put("amount", (int) (money*100));
			nativeParams.put("nonce", RandomUtil.randomString(10));
			nativeParams.put("timestamp", System.currentTimeMillis());
			nativeParams.put("notifyUrl", tszfaaNotifyUrl); // 未初始化
			nativeParams.put("attach",userId+"");


			if (KConstants.PayType.ALIPAY == payType) {
				nativeParams.put("product", "1010");

//				if(1 != SKBeanUtils.getImCoreService().getClientConfig().getEnableAliPay()){
//					return JSONMessage.failureByErrCode(KConstants.ResultCode.FUNCTION_NOTOPEN);
//				}
//
//				orderInfo = AliPayUtil.getOrderInfo("余额充值", "余额充值", price, orderNo);
//				consumeRecordManager.saveConsumeRecord(entity);
//				map.put("orderInfo", orderInfo);
//
//				logger.info("orderInfo : " + orderInfo);
//				return JSONMessage.success(null, map);
			}else if(KConstants.PayType.WXPAY == payType) {
				nativeParams.put("product", "P0000");

//				if(1 != SKBeanUtils.getImCoreService().getClientConfig().getEnableWxPay()){
//					return JSONMessage.failureByErrCode(KConstants.ResultCode.FUNCTION_NOTOPEN);
//				}
//				WxPayDto tpWxPay = new WxPayDto();
//				//tpWxPay.setOpenId(openId);
//				tpWxPay.setBody("余额充值");
//				tpWxPay.setOrderId(orderNo);
//				tpWxPay.setSpbillCreateIp(request.getRemoteAddr());
//				tpWxPay.setTotalFee(price);
//				consumeRecordManager.saveConsumeRecord(entity);
//				Object data= WXPayUtil.getPackage(tpWxPay,wxConfig);
//				return JSONMessage.success(data);
			}else{
				nativeParams.put("product", "1016");
			}
			StringBuilder md5Str = new StringBuilder();
			nativeParams.forEach((key, value) -> md5Str.append(key).append("=").append(value).append("&"));
			md5Str.deleteCharAt(md5Str.length() - 1).append(tszfaaSecret);
			String sign = SecureUtil.md5(md5Str.toString()).toUpperCase();
			nativeParams.put("sign", sign);
			HttpResponse response = HttpRequest.post(tszfaaUrl+"/api/v1/payment/init")
					.body(JSONUtil.toJsonStr(nativeParams),"application/json; charset=utf-8")
					.timeout(15000)
					.execute();
			if(response.getStatus() == 200){
				consumeRecordManager.saveConsumeRecord(entity);
				logger.info("---------------------{}",response.body());
				JSONObject jsonObject = JSONUtil.parseObj(response.body());
				String code = (String) jsonObject.get("code");
				if(!"200".equals(code)){
					return JSONMessage.failure((String) jsonObject.get("msg"));
				}
				String payUrl = (String) jsonObject.getJSONObject("data").getJSONObject("url").get("payUrl");
				map.put("payUrl", payUrl);
				map.put("orderNo",orderNo);
				return JSONMessage.success(null,map);
			}
		}
		return JSONMessage.failureByErrCode(PayResultCode.NotSelectPayType);
	}


/**
　* @Description: 支付宝话费充值
　* @author yushaopeng
　* @date 2025/1/17 16:13
　*/
    @RequestMapping(value = "/getSignV3")
    public JSONMessage getSignV3(HttpServletRequest request, @RequestParam int payType, @RequestParam String price,
                                 @RequestParam(defaultValue="0") long time,
                                 @RequestParam(defaultValue="") String secret, String salt) {

        String token=getAccess_token();
        Integer userId = ReqUtil.getUserId();
        if(StringUtil.isEmpty(salt)){
            //充值接口授权
            if(!authServiceOldUtils.authRedPacket(userId+"", token, time, secret)) {
                return JSONMessage.failureByErrCode(KConstants.ResultCode.AUTH_FAILED);
            }
        }
        // 处理充值自定义输入金额超过两位数
        DecimalFormat df = new DecimalFormat("0.00");
        Double money = new Double(price);
        if(0.01>money){
            return JSONMessage.failureByErrCode(PayResultCode.PleaseEnterAmount);
        }
        // 判断单笔消费金额是否超过限制
        if(money>SKBeanUtils.getImCoreService().getPayConfig().getMaxRechargeAmount()){
            return JSONMessage.failureByErrCode(PayResultCode.ExceedMaxAmount);
        }
        // 判断单日消费金额是否超过限制
        Double todayMoney = consumeRecordManager.getUserPayMoney(userId,KConstants.ConsumeType.USER_RECHARGE,KConstants.OrderStatus.END, DateUtil.getTodayMorning().getTime()/1000 , DateUtil.getTodayNight().getTime()/1000);
        todayMoney = todayMoney + money;
        if(todayMoney > SKBeanUtils.getImCoreService().getPayConfig().getDayMaxRechargeAmount()){
            return JSONMessage.failureByErrCode(PayResultCode.ExceedDayMaxAmount);
        }

        price = df.format(money);
        Map<String,String> map= Maps.newLinkedHashMap();
        String orderInfo="";
        if(0<payType){
            String orderNo=StringUtil.getOutTradeNo();
            BaseConsumeRecord entity=new BaseConsumeRecord();
            entity.setMoney(money);
			/*if(10<entity.getMoney()) {
				return JSONMessage.failureByErrCode(PayResultCode.SingleRechargeUpTen);
			}*/
            entity.setUserId(ReqUtil.getUserId());
            entity.setTime(DateUtil.currentTimeSeconds());
            entity.setType(KConstants.ConsumeType.USER_RECHARGE);
            entity.setChangeType(KConstants.MOENY_ADD);
            entity.setDesc("余额充值");
            //entity.setDesc("Balance recharge");
            entity.setStatus(KConstants.OrderStatus.CREATE);
            entity.setTradeNo(orderNo);
            entity.setPayType(payType);


            /**
            　* @Description:  这里开始请求
            　**/

            if (payType>=1&&payType<=11) {


                Map<String, Object> nativeParams = new TreeMap<>();
                nativeParams.put("mchKey", tszfaaKey);

                nativeParams.put("mchOrderNo", orderNo); // 金额单位为分
                nativeParams.put("amount", (int) (money * 100));
                nativeParams.put("nonce", RandomUtil.randomString(10));
                nativeParams.put("timestamp", System.currentTimeMillis());
                nativeParams.put("notifyUrl", tszfaaNotifyUrl); // 未初始化
                nativeParams.put("attach", userId + "");
                if (KConstants.PayType.ALIPAY == payType) {
                    nativeParams.put("product", "1010");
                }else
                if (KConstants.PayType.ALIPAY2 == payType) {
                    nativeParams.put("product", "1001");

                } else if (KConstants.PayType.ATLSPAY == payType) {
                    nativeParams.put("product", "1009");

                }else if (KConstants.PayType.NUMBERPAY == payType) {
                    nativeParams.put("product", "1013");

                }

                else {
                    nativeParams.put("product", "1016");
                }
                StringBuilder md5Str = new StringBuilder();
                nativeParams.forEach((key, value) -> md5Str.append(key).append("=").append(value).append("&"));
                md5Str.deleteCharAt(md5Str.length() - 1).append(tszfaaSecret);
                String sign = SecureUtil.md5(md5Str.toString()).toUpperCase();
                nativeParams.put("sign", sign);
                HttpResponse response = HttpRequest.post(tszfaaUrl + "/api/v1/payment/init")
                        .body(JSONUtil.toJsonStr(nativeParams), "application/json; charset=utf-8")
                        .timeout(15000)
                        .execute();
                if (response.getStatus() == 200) {
                    consumeRecordManager.saveConsumeRecord(entity);
                    logger.info("---------------------{}", response.body());
                    JSONObject jsonObject = JSONUtil.parseObj(response.body());
                    String code = (String) jsonObject.get("code");
                    if (!"200".equals(code)) {
                        return JSONMessage.failure((String) jsonObject.get("msg"));
                    }
                    String payUrl = (String) jsonObject.getJSONObject("data").getJSONObject("url").get("payUrl");
                    map.put("payUrl", payUrl);
                    map.put("orderNo", orderNo);
                    return JSONMessage.success(null, map);
                }
            }
            else if (payType<=15&&payType>=12){
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("mchId", 20000094 + "");  //商户ID
                params.put("appId", "e23df2dde01b40289fdb1ca132c34876");  //商户应用ID
                if (KConstants.PayType.ALIPAY3==payType ) {
                    params.put("productId", "8008");  //支付产品ID
                }else if (KConstants.PayType.MBANK2==payType){
                    params.put("productId", "8028");  //支付产品ID
                }else if (KConstants.PayType.ALIPAY4==payType){
                    params.put("productId", "8040");  //支付产品ID
                }else {
                    params.put("productId", "8020");  //支付产品ID
                }
                params.put("mchOrderNo", orderNo);   //商户订单号
                params.put("currency", "cny");   //币种
                params.put("amount", (int) (money * 100));   //支付金额
                params.put("clientIp", "210.73.10.148");   //客户端IP
                params.put("device", "ios10.3.1");   //客户端设备
//                params.put("returnUrl", "http://localhost:8080/return_page.html");   //支付结果前端跳转URL
                params.put("notifyUrl", kkzfNotifyUrl);   //支付结果后台回调URL
                params.put("subject", "网络购物");  //商品主题
                params.put("body", "网络购物");   //商品描述信息
                params.put("param1", userId + "");   //扩展参数1
                params.put("param2", orderNo);   //扩展参数2
                params.put("extra", "");  //附加参数
                params.put("reqTime", com.basic.im.pay.controller.secondpay.utils.DateUtil.date2Str(new Date(), com.basic.im.pay.controller.secondpay.utils.DateUtil.FORMAT_YYYYMMDDHHMMSS));  //请求时间, 格式yyyyMMddHHmmss
                params.put("version", "1.0");  //版本号, 固定参数1.0

                String sign = SignUtil.getSign(params, "1RWGEGISF4GGPDWF2WXDVJ4OCFZKFBKGVZBFQLSLHWKTMYHXN0FYPXZ8BM63KSJ8Z6H0QQIW5W1SSKFVBY64CTZFVEAAKCQUAWLZMHEFYEO7FFBR61L3XWTEJ4FWYS2X");  //签名
                params.put("sign", sign);

                try {
                    String result = HttpUtil.post("https://wg.kkzf.xyz" + "/api/pay/create_order", genUrlParams(params));
                    JSONObject jsonObject = JSONUtil.parseObj(result);
                    String code = (String) jsonObject.get("retCode");
                    if (!"SUCCESS".equals(code)) {
                        return JSONMessage.failure((String) jsonObject.get("retMsg"));
                    }
                    consumeRecordManager.saveConsumeRecord(entity);
                    map.put("payUrl", (String) jsonObject.get("payUrl"));
                    map.put("orderNo", orderNo);
                    return JSONMessage.success(null, map);
                } catch (IOException e) {
                    e.printStackTrace();
                    return JSONMessage.failureByErrCode(PayResultCode.NotSelectPayType);
                }
            }else if (payType==16){

                // 请求参数
                Map<String, Object> params = new TreeMap<>();
                params.put("merch_no", "10225");
                String orderno = StringUtil.getOutTradeNo();
                System.out.println(orderno);
                params.put("merch_order_no", orderno);
                params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
                params.put("order_amount", money);
                params.put("order_currency", "CNY");
                params.put("channel_code", "801");
                params.put("notify_url", "https://www.test.com/notify.htm");
                params.put("return_url", "http://43.199.8.90:8095/alipay/thirdnotify");
                params.put("order_language", "CN");
                params.put("merch_user_id", ReqUtil.getUserId());
                params.put("request_ip", ReqUtil.getRequestIp());

                // 生成签名
                String sign = SignUtil.getSign2(params, MERCHANT_KEY);
                params.put("sign", sign);

                // 发送POST请求
                try {
                    String result = ThirdPay.sendPostRequest(ThirdPay.API_GATEWAY, params);
                    JSONObject jsonObject = JSONUtil.parseObj(result);
                    String code = String.valueOf( jsonObject.get("code"));
                    if (!"1".equals(code)) {
                        return JSONMessage.failure((String) jsonObject.get("info"));
                    }
                    consumeRecordManager.saveConsumeRecord(entity);
                    map.put("payUrl",  jsonObject.getJSONObject("data").getStr("pay_url"));
                    map.put("orderNo", orderNo);
                    return JSONMessage.success(null, map);


                }catch (Exception e){
                    logger.error(e.getMessage());
                    e.printStackTrace();
                    return JSONMessage.failureByErrCode(PayResultCode.NotSelectPayType);
                }

            }
        }
        return JSONMessage.failureByErrCode(PayResultCode.NotSelectPayType);
    }


    @RequestMapping(value = "/getSignV4")
    public JSONMessage getSignV4(HttpServletRequest request, @RequestParam int payType, @RequestParam String price,
                                 @RequestParam(defaultValue="0") long time,
                                 @RequestParam(defaultValue="") String secret, String salt) {

        String token=getAccess_token();
        Integer userId = ReqUtil.getUserId();
        if(StringUtil.isEmpty(salt)){
            //充值接口授权
            if(!authServiceOldUtils.authRedPacket(userId+"", token, time, secret)) {
                return JSONMessage.failureByErrCode(KConstants.ResultCode.AUTH_FAILED);
            }
        }
        // 处理充值自定义输入金额超过两位数
        DecimalFormat df = new DecimalFormat("0.00");
        Double money = new Double(price);
        if(0.01>money){
            return JSONMessage.failureByErrCode(PayResultCode.PleaseEnterAmount);
        }
        // 判断单笔消费金额是否超过限制
        if(money>SKBeanUtils.getImCoreService().getPayConfig().getMaxRechargeAmount()){
            return JSONMessage.failureByErrCode(PayResultCode.ExceedMaxAmount);
        }
        // 判断单日消费金额是否超过限制
        Double todayMoney = consumeRecordManager.getUserPayMoney(userId,KConstants.ConsumeType.USER_RECHARGE,KConstants.OrderStatus.END, DateUtil.getTodayMorning().getTime()/1000 , DateUtil.getTodayNight().getTime()/1000);
        todayMoney = todayMoney + money;
        if(todayMoney > SKBeanUtils.getImCoreService().getPayConfig().getDayMaxRechargeAmount()){
            return JSONMessage.failureByErrCode(PayResultCode.ExceedDayMaxAmount);
        }

        price = df.format(money);
        Map<String,String> map= Maps.newLinkedHashMap();
        String orderInfo="";
        if(0<payType){
            String orderNo=StringUtil.getOutTradeNo();
            BaseConsumeRecord entity=new BaseConsumeRecord();
            entity.setMoney(money);
			/*if(10<entity.getMoney()) {
				return JSONMessage.failureByErrCode(PayResultCode.SingleRechargeUpTen);
			}*/
            entity.setUserId(ReqUtil.getUserId());
            entity.setTime(DateUtil.currentTimeSeconds());
            entity.setType(KConstants.ConsumeType.USER_RECHARGE);
            entity.setChangeType(KConstants.MOENY_ADD);
            entity.setDesc("余额充值");
            //entity.setDesc("Balance recharge");
            entity.setStatus(KConstants.OrderStatus.CREATE);
            entity.setTradeNo(orderNo);
            entity.setPayType(payType);

            Map<String, Object> nativeParams = new TreeMap<>();
            nativeParams.put("mchKey", tszfaaKey);

            nativeParams.put("mchOrderNo", orderNo); // 金额单位为分
            nativeParams.put("amount", (int) (money*100));
            nativeParams.put("nonce", RandomUtil.randomString(10));
            nativeParams.put("timestamp", System.currentTimeMillis());
            nativeParams.put("notifyUrl", tszfaaNotifyUrl); // 未初始化
            nativeParams.put("attach",userId+"");


            if (KConstants.PayType.ALIPAY == payType) {
                nativeParams.put("product", "1009");

//				if(1 != SKBeanUtils.getImCoreService().getClientConfig().getEnableAliPay()){
//					return JSONMessage.failureByErrCode(KConstants.ResultCode.FUNCTION_NOTOPEN);
//				}
//
//				orderInfo = AliPayUtil.getOrderInfo("余额充值", "余额充值", price, orderNo);
//				consumeRecordManager.saveConsumeRecord(entity);
//				map.put("orderInfo", orderInfo);
//
//				logger.info("orderInfo : " + orderInfo);
//				return JSONMessage.success(null, map);
            }else if(KConstants.PayType.WXPAY == payType) {
                nativeParams.put("product", "P0000");

//				if(1 != SKBeanUtils.getImCoreService().getClientConfig().getEnableWxPay()){
//					return JSONMessage.failureByErrCode(KConstants.ResultCode.FUNCTION_NOTOPEN);
//				}
//				WxPayDto tpWxPay = new WxPayDto();
//				//tpWxPay.setOpenId(openId);
//				tpWxPay.setBody("余额充值");
//				tpWxPay.setOrderId(orderNo);
//				tpWxPay.setSpbillCreateIp(request.getRemoteAddr());
//				tpWxPay.setTotalFee(price);
//				consumeRecordManager.saveConsumeRecord(entity);
//				Object data= WXPayUtil.getPackage(tpWxPay,wxConfig);
//				return JSONMessage.success(data);
            }else{
                nativeParams.put("product", "1016");
            }
            StringBuilder md5Str = new StringBuilder();
            nativeParams.forEach((key, value) -> md5Str.append(key).append("=").append(value).append("&"));
            md5Str.deleteCharAt(md5Str.length() - 1).append(tszfaaSecret);
            String sign = SecureUtil.md5(md5Str.toString()).toUpperCase();
            nativeParams.put("sign", sign);
            HttpResponse response = HttpRequest.post(tszfaaUrl+"/api/v1/payment/init")
                    .body(JSONUtil.toJsonStr(nativeParams),"application/json; charset=utf-8")
                    .timeout(15000)
                    .execute();
            if(response.getStatus() == 200){
                consumeRecordManager.saveConsumeRecord(entity);
                logger.info("---------------------{}",response.body());
                JSONObject jsonObject = JSONUtil.parseObj(response.body());
                String code = (String) jsonObject.get("code");
                if(!"200".equals(code)){
                    return JSONMessage.failure((String) jsonObject.get("msg"));
                }
                String payUrl = (String) jsonObject.getJSONObject("data").getJSONObject("url").get("payUrl");
                map.put("payUrl", payUrl);
                map.put("orderNo",orderNo);
                return JSONMessage.success(null,map);
            }
        }
        return JSONMessage.failureByErrCode(PayResultCode.NotSelectPayType);
    }


	@ApiOperation("用户充值记录列表")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query" , name="pageIndex" , value="当前页码数",dataType="int"),
		@ApiImplicitParam(paramType="query" , name="pageSize" , value="每页数据条数",dataType="int",defaultValue="10")
	})
	@RequestMapping("/user/recharge/list")
	public JSONMessage getList(@RequestParam(defaultValue="0")int pageIndex, @RequestParam(defaultValue="10")int pageSize) {
		List<BaseConsumeRecord> pageData = consumeRecordManager.reChargeList(ReqUtil.getUserId(), pageIndex, pageSize);



		long total=pageData.size();
		return JSONMessage.success(new PageVO(pageData, total,pageIndex, pageSize));
	}
	

	@ApiOperation("用户消费记录列表 ")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query" , name="pageIndex" , value="当前页码数",dataType="int"),
		@ApiImplicitParam(paramType="query" , name="pageSize" , value="每页数据条数",dataType="int",defaultValue = "10")
	})
	@RequestMapping("/user/consumeRecord/list")
	public JSONMessage consumeRecordList(@RequestParam(defaultValue="0")int pageIndex,@RequestParam(defaultValue="10")int pageSize) {
		try {
			PageResult<BaseConsumeRecord> result = consumeRecordManager.consumeRecordList(ReqUtil.getUserId(), pageIndex, pageSize,(byte)0);

			if(!ReqUtil.DEFAULT_LANG.equals(ReqUtil.getRequestLanguage())){
				Locale requestLocale = LocaleMessageUtils.getRequestLocale();
				result.getData().forEach(data->{
					data.setDesc(LocaleMessageUtils.getMessage(ConsumeRecordEnum.getCode(data.getType()),requestLocale));

				});
			}
			PageVO data = new PageVO(result.getData(),result.getCount(),pageIndex,pageSize);
			return JSONMessage.success(data);
		} catch (ServiceException e) {
			return JSONMessage.failureByException(e);
		}
		
	}

	@ApiOperation("消费列表")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType="query" , name="pageIndex" , value="当前页码数",dataType="int",defaultValue = "0"),
			@ApiImplicitParam(paramType="query" , name="pageSize" , value="每页数据条数",dataType="int",defaultValue = "10"),
			@ApiImplicitParam(paramType="query" , name="toUserId" , value="发送方编号",dataType="int",defaultValue = "0")
	})
	@RequestMapping("/friend/consumeRecordList")
	public JSONMessage friendRecordList(@RequestParam(defaultValue="0")int toUserId,@RequestParam(defaultValue="0")int pageIndex,@RequestParam(defaultValue="10")int pageSize) {
		try {
			PageResult<BaseConsumeRecord> result = consumeRecordManager
					.friendRecordList(ReqUtil.getUserId(),toUserId, pageIndex, pageSize,(byte)0);
			if(0==result.getCount()) {
                return JSONMessage.success(null, null);
            }
			// 国际化
			if(!ReqUtil.DEFAULT_LANG.equals(ReqUtil.getRequestLanguage())){
				Locale requestLocale = LocaleMessageUtils.getRequestLocale();
				result.getData().forEach(consumeRecord->{
					consumeRecord.setDesc(LocaleMessageUtils.getMessage(ConsumeRecordEnum.getCode(consumeRecord.getType()),requestLocale));
				});
			}
			PageVO data = new PageVO(result.getData(),result.getCount(),pageIndex,pageSize);
			return JSONMessage.success(data);
		} catch (ServiceException e) {
			return JSONMessage.failureByException(e);
		}
		
	}
	
	

	@ApiOperation("删除消费记录 ")
	@ApiImplicitParam(paramType="query" , name="id" , value="记录Id",dataType="String",required=true)
	@RequestMapping("/recharge/delete")
	public JSONMessage delete(String id) {
		Object data = consumeRecordManager.getConsumeReCord(ReqUtil.getUserId(),new ObjectId(id));
		if(null != data){
			consumeRecordManager.getConsumeRecordDao().deleteById(ReqUtil.parseId(id));
			return JSONMessage.success();
		}else{
			return JSONMessage.failure(null);
		}
	}


	@ApiOperation("按月查询消费记录统计 ")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query" , name="startTime" , value="开始时间",dataType="String",required=true),
		@ApiImplicitParam(paramType="query" , name="endTime" , value="结束时间",dataType="String",required=true),
		@ApiImplicitParam(paramType="query" , name="pageIndex" , value="页码",dataType="String"),
		@ApiImplicitParam(paramType="query" , name="pageSize" , value="翻页大小",dataType="String"),
		@ApiImplicitParam(paramType="query" , name="needCount" , value="是否需要统计 1:需要 ,0 不需要",dataType="int",required=true),
			@ApiImplicitParam(paramType="query" , name="isNext" , value="是否下拉 1:下拉 ,0 上拉",dataType="int",required=true),
	})

	@RequestMapping("/consumeRecord/queryConsumeRecordCount")
	public JSONMessage queryConsumeRecordCount(long startTime, long endTime,@RequestParam(defaultValue = "0") int pageIndex,@RequestParam(defaultValue = "50") int pageSize, int needCount,int isNext) {

		Integer userId = ReqUtil.getUserId();
		boolean needCountBool=1==needCount?true:false;
		boolean next=1==isNext?true:false;
		ConsumRecordCountDTO consumRecordCountDTO = consumeRecordManager.queryConsumeRecordCount(userId, startTime, endTime, pageIndex, pageSize,needCountBool,next);
//		if(!ReqUtil.DEFAULT_LANG.equals(ReqUtil.getRequestLanguage())){
//			Locale requestLocale = LocaleMessageUtils.getRequestLocale();
//			consumRecordCountDTO.getRecordList().forEach(data->{
//				data.setDesc(LocaleMessageUtils.getMessage(ConsumeRecordEnum.getCode(data.getType()),requestLocale));
//
//			});
//		}

		return JSONMessage.success(consumRecordCountDTO);
	}



}
